<template>
  <div style="text-align: center">
    <el-input
        slot="reference"
        style="width: 80% ;margin: 0 10px"
        size="medium"
        placeholder="请输入内容"
        v-model="keyword"
        @input="searchPoem(1)"
        clearable>
    </el-input>
    <ul class="result-container flex-col al-center">
      <li v-for="(item,index) in searchList" :key="index" class="result-item">
        <h4><a href="javascript:;" @click="goPoemItem(item.pid,'宣州谢朓')" v-html="formatText(item.ptitle)"></a></h4>
        <p>[{{ item?.authors.adynasty }}]·<a href="javascript:;" @click="goAuthorItem(item?.authors.aid, item?.authors.aname)">{{ item?.authors.aname }}</a></p>
        <p v-html="formatText(item.pcontent)"></p>
      </li>
    </ul>
    <el-pagination
        :page-size="10"
        :pager-count="11"
        @current-change="currentChange"
        layout="prev, pager, next"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>
import _ from 'lodash'
import {reqSearchPoem} from '@/API/modules/poem'
import router from '@/router'


export default {
  name: "SearchPoemAndLine",
  data() {
    return {
      keyword: "",
      searchList: [],
      total: 30,

    }
  },
  methods: {
    searchPoem: _.throttle(async function (page) {
      let result = await reqSearchPoem(page, this.keyword)
      if (result.status == 200) {
        this.searchList = result.data.data.poemsAndAuthorsList
        this.total = result.data.data.total
      }
    }, 500),
    goPoemItem(id, bread) {
      //在出发地印上目的地的名字
      this.$route.meta.toBreadName = bread;
      router.push(`/poemItem/${id}`)
    },
    goAuthorItem(id, bread) {
      //在出发地印上目的地的名字
      this.$route.meta.toBreadName = bread;
      router.push(`/authorItem/${id}`)
    },
    formatText(str) {
      let regKeyword = new RegExp(`${this.keyword}`, 'g')
      if (str.length > 140) {
        let regKeywordExpend = new RegExp("[一-龟]*?，?[一-龟]*?"+this.keyword+"[一-龟]*?(。|，)[一-龟]*?(？|！|。|，)")
        str =  str.match(regKeywordExpend)?str.match(regKeywordExpend)[0]:null
        if (str == null) return '这首诗里没有这个字，并且太长了显示不下了'

      }
      return str.replace(regKeyword, `<span style="color: red">${this.keyword}</span>`)
    },
    currentChange(val){
      this.searchPoem(val)
    }
  }
}
</script>

<style lang="scss" scoped>
p {
  margin: 0;
}

.result-container {

  padding: 0;


  .result-item {
    overflow: hidden;
    text-align: left;
    border: 1px solid #c5c5c5;
    width: 80%;
    height: 140px;
    padding: 7px 28px;
    background-color: #ffffff;

    > &:nth-child(2n) {
      transform: skew(10deg);
    }

    > &:nth-child(2n-1) {
      transform: skew(-10deg);
    }
  }
}
</style>